#include "HalPWM.h"

// #define HAL_PWM_OUT_CH_COUNT 8

extern TIM_HandleTypeDef htim7;
static volatile uint16_t g_pluseCount = 0;
static HalPWMInfo_t g_pwmInfo[HAL_PWM_OUT_CH_COUNT];

extern uint16_t SysGetPWMCount(void);
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
    uint8_t i;
    if(htim == &htim7)
    {
        g_pluseCount++;
        if(g_pluseCount >= SysGetPWMCount())
        {
            for(i = 0; i < HAL_PWM_OUT_CH_COUNT; i++)
            {
                if(g_pwmInfo[i].enable && g_pwmInfo[i].duty > 0)
                {
                    HAL_GPIO_WritePin(g_pwmInfo[i].io.port, g_pwmInfo[i].io.pin, GPIO_PIN_SET);
                }
            }
            g_pluseCount = 0;
        }
        else
        {
            for(i = 0; i < HAL_PWM_OUT_CH_COUNT; i++)
            {
                if(g_pwmInfo[i].enable)
                {
                    if( g_pluseCount >= g_pwmInfo[i].duty)
                    {
                        HAL_GPIO_WritePin(g_pwmInfo[i].io.port, g_pwmInfo[i].io.pin, GPIO_PIN_RESET);
                    }
                    else
                    {
                        HAL_GPIO_WritePin(g_pwmInfo[i].io.port, g_pwmInfo[i].io.pin, GPIO_PIN_SET);
                    }
                }
            }
        }
    }
}

void HalPWMDutySet(uint8_t ch, uint16_t val)
{
    if(ch < HAL_PWM_OUT_CH_COUNT && g_pwmInfo[ch].duty != val)
    {
        __disable_irq(); 
        if(g_pwmInfo[ch].enable)
        {
            g_pwmInfo[ch].duty = val;
        }
        __enable_irq(); 
    }
}

void HalPWMChannelStart(uint8_t ch, uint16_t duty, GPIO_TypeDef *port, uint16_t pin)
{
    __disable_irq(); 
    if(ch < HAL_PWM_OUT_CH_COUNT)
    {
        g_pwmInfo[ch].enable = true;
        g_pwmInfo[ch].duty = duty;
        g_pwmInfo[ch].io.port = port;
        g_pwmInfo[ch].io.pin = pin;
    }
    __enable_irq();
}

void HalPWMInitialize(void)
{
    HAL_TIM_Base_Start_IT(&htim7);
    memset(g_pwmInfo, 0, sizeof(HalPWMInfo_t) * HAL_PWM_OUT_CH_COUNT);
    g_pluseCount = 0;
}
